﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;

using ABCat.Core;
using ABCat.Core.Plugins;
using ABCat.Core.Plugins.DataSets;
using ABCat.Core.Plugins.UI;
using ABCat.Shared.Properties;

namespace ABCat.Plugins.BrowserWindow.WPFWebBrowser
{
	/// <summary>
	/// Interaction logic for WPFWebBrowser.xaml
	/// </summary>
	[PluginCreator("Browser Window on WPF.WebBrowser", WorkModeEnum.PerContext),
	UsedImplicitly]
	public partial class WPFWebBrowserWindowPlugin : IBrowserWindowPlugin
	{
		#region + Events +

		public event EventHandler Disposed;
		public event EventHandler WindowClosed;

		#endregion
		#region + Fields +

		private Context _context;
		private string _previousFileName;

		#endregion
		#region + Properties +

		public bool IsDisplayed
		{
			get { return Visibility == Visibility.Visible; }
		}

		#endregion
		#region + Ctor +

		public WPFWebBrowserWindowPlugin(Context context)
		{
			InitializeComponent();
			_context = context;
		}

		#endregion
		#region + Logic +

		public bool CheckForConfig(bool correct, out Config incorrectConfig)
		{
			incorrectConfig = null;
			return true;
		}

		public Config Config { get; set; }

		public void Display()
		{
			Show();
		}

		public void Dispose()
		{
			WebBrowser.Dispose();
			Disposed.Fire(this);
		}

		public void RestoreLayout()
		{
		}

		public FrameworkElement Control
		{
			get
			{
				return this;
			}
		}

		public void ShowRecordPage(string title, string pageHtml)
		{
			if (!string.IsNullOrEmpty(_previousFileName) && File.Exists(_previousFileName)) File.Delete(_previousFileName);
			_previousFileName = null;

			pageHtml = "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head>" + pageHtml;
			_previousFileName = Path.GetTempFileName() + ".html";
			File.WriteAllText(_previousFileName, pageHtml);
			WebBrowser.Navigate(_previousFileName);
			Title = title;
		}

		public void StoreLayout()
		{
		}

		protected override void OnClosed(EventArgs e)
		{
			base.OnClosed(e);
			var windowClosed = WindowClosed;
			if (windowClosed != null) windowClosed(this, e);
		}

		#endregion
	}
}